package com.ze.familyday.familyphotoframe;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
   
import com.umeng.analytics.MobclickAgent;
import com.umeng.common.net.t;
import com.ze.commontool.CustomDialog;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.familyday.familyphotoframe.R;
import com.ze.familydayverpm.userinfo.Componet;
import com.ze.familydayverpm.userinfo.UserInfoManager;
import com.ze.model.DataModel;
import com.ze.model.ModelDataMgr;
import com.ze.model.PhotoModel;
import com.ze.model.PhotoModel.PicInfo;


import android.app.AlertDialog;  
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Resources.Theme;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	public final static String TAG = "MainActivity";
	//
	ArrayList<DataModel> arrayList = null;
	String  mUidString;
	int currentPage = 0;
	View wifiView;
	ListView wifiListView;
	View loginView;
	private 		BroadcastReceiver receiver ;
	private 		IntentFilter				filter;
	public static MainActivity instance;
	WifiManager wifiManager;
	ConnectivityManager conMan;
	AlertDialog wifiProgressDialog ;
	View 			view_progress;
	TextView		tv_progress;
	ImageButton		btn_progress;
	RelativeLayout mainLayout;
	BroadcastReceiver wifiStateReceive = null;
	IntentFilter wifiFilter = null;
	Context mContext;
	/**
	 * 电量提示对话框
	 */
	Dialog batteryDialog;
	/**
	 * 电量提示对话框信息
	 */
	TextView BD_notice;
	/**
	 * 电量提示对话框按钮
	 */
	TextView BD_btn;
	
	/**
	 * wifi连接提示框
	 */
	Dialog wifiNoticeDialog;
	/**
	 * wifi连接提示框设置按钮
	 */
	Button WND_settingBtn;
	/**
	 * wifi连接提示框离线使用按钮
	 */
	Button WND_useNoWifiBtn;
	/**
	 * 充电状态
	 */
	public static int currentPlugged = 0;
	public static int lastPlugged = 0;
	int type = -1;
	
	/**
	 * 当前电量
	 */
	int currentLevel = -1;
	Dialog startDialog = null;
	Dialog loginDialog;
	/**
	 * 测试添加按钮
	 */
	Button settingBtn;
	Toast toast;
	View toastView;
	TextView toastTxt;
	
	WifiLock wifiLock;
	
	LinearLayout mRoot;
	Button btn1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");
		setContentView(R.layout.activity_pic);
		mContext = this;
		
		mRoot = (LinearLayout) findViewById(R.id.root);
		btn1 = (Button) findViewById(R.id.btn1);
		//设置提示的toast
		toast = Toast.makeText(mContext, "", Toast.LENGTH_LONG);
		toastView = getLayoutInflater().inflate(R.layout.toast_text, null);
		toastTxt = (TextView) toastView.findViewById(R.id.toast_txt);
		wifiView  = findViewById(R.id.signin_btnSignWifi);
		loginView = findViewById(R.id.signin_loginview);
		wifiView.setOnClickListener(onClickListener);
		mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
		mainLayout.setOnClickListener(onClickListener);
		dialog_login					= findViewById(R.id.signin_btnSignIn);
		dialog_etUser 					= (EditText)findViewById(R.id.signin_etUser);
		Componet userComponet = UserInfoManager.getInstance(MainActivity.this).getItem("username");
		if ( userComponet != null ) {
			dialog_etUser.setText( userComponet.getValue() );
		}
		dialog_etPw					= (EditText)findViewById(R.id.signin_etPw);
		dialog_login.setOnClickListener(onClickListener);
		loginView.setVisibility(View.INVISIBLE);
		instance = this;
		
		//初始化 wifi连接提示框
		if (wifiNoticeDialog == null) {
			wifiNoticeDialog = new CustomDialog(mContext, 410, 250, R.layout.dialog_notice_layout,
					R.style.FullHeightDialog);
			wifiNoticeDialog.setCanceledOnTouchOutside(false);
			View view = getLayoutInflater().inflate(R.layout.dialog_notice_layout, null);
			WND_settingBtn = (Button) view.findViewById(R.id.dn_cancel);
			WND_settingBtn.setText("setting");
			WND_settingBtn.setOnClickListener(onClickListener);
			WND_useNoWifiBtn = (Button) view.findViewById(R.id.dn_OK);
			WND_useNoWifiBtn.setText("offline");
			WND_useNoWifiBtn.setOnClickListener(onClickListener);
			((TextView) view.findViewById(R.id.dn_notice)).setText("please set up wifi!");
			//ED_notice.setText("是否要退出账号？");
			wifiNoticeDialog.setContentView(view);
		}
		
		//初始化电量提示框
		if (batteryDialog == null){
			batteryDialog = new CustomDialog(mContext, 450, 250, R.layout.dialog_notice_layout,
					R.style.FullHeightDialog);
			batteryDialog.setCanceledOnTouchOutside(true);
			View view = getLayoutInflater().inflate(R.layout.dialog_notice_layout, null);
			BD_notice = (TextView) view.findViewById(R.id.dn_notice);
			BD_notice.setText("充电提示");
			BD_btn = (Button) view.findViewById(R.id.dn_cancel);
			BD_btn.setText("OK");
			BD_btn.setOnClickListener(onClickListener);
			((Button) view.findViewById(R.id.dn_OK)).setVisibility(View.GONE);
			batteryDialog.setContentView(view);
		}
		loginDialog = new Dialog(mContext, R.style.FullHeightDialog);
		//loginDialog.setContentView(R.layout.define_progress_dialog);
		loginDialog.setCanceledOnTouchOutside(false);
		view_progress = getLayoutInflater().inflate(R.layout.define_progress_dialog, null);
		tv_progress = (TextView)view_progress.findViewById(R.id.dpd_tv);
		btn_progress = (ImageButton)view_progress.findViewById(R.id.dpd_btn);
		btn_progress.setOnClickListener(onClickListener);
		loginDialog.setContentView(view_progress);
		
		//wifiProgressDialog = new AlertDialog.Builder(this).setView(view_progress).create();
		//wifiProgressDialog.setCanceledOnTouchOutside(false);
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiManager.setWifiEnabled(true);
		conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		
		receiver = new WifiReceiverInMain();
		filter = new IntentFilter();
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION );
		filter.addAction(WifiManager.EXTRA_SUPPLICANT_ERROR);
		//registerReceiver(receiver, filter);
		
		//注册监测wifi状态的广播
		//wifiStateReceive = new WifiStateReceive(wifiView);
		wifiStateReceive = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
				//获得网络连接服务   
			    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);   
			    // State state = connManager.getActiveNetworkInfo().getState();   
			    // 获取WIFI网络连接状态  
			    State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();   
			    // 判断是否正在使用WIFI网络   
			    if (State.CONNECTED == state) {
			    	Log.v(TAG, "WIFI网络");
			    	MainActivity.WIFI_STATE = 1;
			    	new Handler().post(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							wifiView.setBackgroundResource(R.drawable.main_wifi_on);
						}
					});
			    	
			    } else {
			    	Log.v(TAG, "没有WIFi网络");
			    	MainActivity.WIFI_STATE = 0;
			    	new Handler().post(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							wifiView.setBackgroundResource(R.drawable.main_wifi);
						}
					});
			    }
				} else if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
					type = intent.getIntExtra("plugged", -1);
					lastPlugged = currentPlugged;
					currentPlugged = type;
					if (lastPlugged != currentPlugged)
						isFirstFull = false;
					Log.v(TAG, "上次充电类型：" + lastPlugged);
					Log.v(TAG, "这次充电类型：" + currentPlugged);
					Log.v(TAG, "充电类型：" + type);
					int level = intent.getIntExtra("level", -1);
					int scale = intent.getIntExtra("scale", -1);
					if (level >= 0 && scale > 0)
						currentLevel = (level * 100) / scale;
					if (batteryDialog != null && batteryDialog.isShowing())
						batteryDialog.dismiss();
					
					if (type == 1 && currentLevel >= 100 && !isFirstFull){
						isFirstFull = true;
						//batteryDialog.setMessage("充电已完成！");
						BD_notice.setText("Full Battery!");
						batteryDialog.show();
					} else if (type == 1 && lastPlugged != currentPlugged) {
						BD_notice.setText("Battery：" + currentLevel + "%");
						batteryDialog.show();
					}
					
				}
				
			}
		};
		wifiFilter = new IntentFilter();
		wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		wifiFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(wifiStateReceive, wifiFilter);
		stateRegister = true;
		
		//By mouse 锁定wifi不休眠
		WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiLock = manager.createWifiLock("SwiFTP");
		wifiLock.setReferenceCounted(false);
		wifiLock.acquire();
		
		//By mouse 停止服务
		Intent stopIntent = new Intent(mContext, PullImageService.class);
		mContext.stopService(stopIntent);
		Log.v(PullImageService.TAG, "停止服务！");
		//控制弹出键盘时 view上升高度
		controlKeyboardLayout(mRoot, btn1);
		
	}
	public static boolean isFirstFull = false;
	
	public static boolean hasInitialization = false;
	
	
	/**
	 * By mouse
	 * @author Administrator
	 *
	 */
	class InitializationTask extends AsyncTask<Object, Object, Object>{

		//startDialog = null;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if (hasInitialization){
				return;
			}
			if (startDialog == null)
				startDialog = new Dialog(mContext, R.style.FullHeightDialog);
			//View initView = getLayoutInflater().inflate(R.layout.initial, null);
			startDialog.setContentView(R.layout.initial);
			//startDialog.setMessage("正在初始化...");
			startDialog.setCanceledOnTouchOutside(false);
			if (!startDialog.isShowing())
				startDialog.show();
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			int countTime = 0;
			/*
			*/
			if (!hasInitialization){
				while (WIFI_STATE != 1 && countTime < 20){
					myDelay(1000);
					countTime ++;
				}
				Log.v(TAG, "第一次初始化所用的时间countTime:" + countTime);
			}
			Log.v(TAG, "断点111");
			/*else {
				countTime = 0;
				while (WIFI_STATE == -1 && countTime < 5){
					myDelay(1000);
					countTime ++;
				}
				Log.v(TAG, "非第一次初始化所用的时间countTime:" + countTime);
			}*/
			
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.v(TAG, "断点222");
			if (!hasInitialization && startDialog != null && startDialog.isShowing())
				startDialog.dismiss();
			hasInitialization = true;
			//wifi已连接的状态
			if (WIFI_STATE == 1){
				if ( UserInfoManager.getInstance(MainActivity.this).getItem("m_auth") != null ) {
					Log.v(TAG, "进入点1");
					isSaveMauth = true;
					downloadPicTask();
				} else {
					Log.v(TAG, "进入点2");
					isSaveMauth = false;
					showLoginDialog();
				}
			} else {
				Log.v(TAG, "进入点3");
				loginView.setVisibility(View.INVISIBLE);
				if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
					wifiNoticeDialog.show();
				}
				
			}
			
		}
		
	}
	boolean stateRegister = false;
	public static int WIFI_STATE = 0;
	boolean flagHasStart = false;
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.v(TAG, "onDestroy");
		if (stateRegister){
			stateRegister = false;
			unregisterReceiver(wifiStateReceive);
		}
		
		if( wifiLock != null && wifiLock.isHeld() )
		{
			wifiLock.release();
		}
		
		isDestroy = true;
		//hasInitialization = false;
//		unregisterReceiver(receiver);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
		Log.v(TAG, "resume");
		//registerReceiver(receiver, filter);
		//onEnterFrame();
		if (!hasInitialization) {
			new InitializationTask().execute("");
		} else {
			if (WIFI_STATE == 1){
				if ( UserInfoManager.getInstance(MainActivity.this).getItem("m_auth") != null ) {
					Log.v(TAG, "进入点1");
					isSaveMauth = true;
					downloadPicTask();
				} else {
					Log.v(TAG, "进入点2");
					isSaveMauth = false;
					showLoginDialog();
				}
			} else {
				Log.v(TAG, "进入点3");
				loginView.setVisibility(View.INVISIBLE);
				if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
					wifiNoticeDialog.show();
				}
			}
		}
		
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.v(TAG, "onPause");
		MobclickAgent.onPause(this);
		if (startDialog != null)
			startDialog.dismiss();
		if (batteryDialog != null)
			batteryDialog.dismiss();
		Log.v(TAG, "onPause");
		//loginThread.stop();
//		unregisterReceiver(receiver);
	}
	
	int testNum = 0;
	/**
	 * 
	 */
	public void onEnterFrame()
	{
		Log.v("cube", "第" + testNum + "次调用");
		testNum ++;
		 ConnectivityManager connectivityManager=(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
		 NetworkInfo net=connectivityManager.getActiveNetworkInfo();
		if( uselocal  || (net != null && net.isConnected()) )
		{
			if ( UserInfoManager.getInstance(MainActivity.this).getItem("m_auth") != null ) {
				isSaveMauth = true;
				downloadPicTask();
			}else
			{
				isSaveMauth = false;
				showLoginDialog();
			}
		}else
		{
			// 去掉等待自动扫描
			if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
				wifiNoticeDialog.show();
			}
//			if( ishaveOpenWifi )
//			{
//				netErrorDialog.show();
//			}else
//			{
//				wifiProgressDialog.setMessage("正在连接wifi");
//				tv_progress.setText("正在连接wifi");
//				wifiProgressDialog.show();
//				waitConnect(20*1000);
//			}
		}
	}
	public boolean uselocal = false;
	public boolean isSaveMauth = false;
	
	private boolean loadListTaskFlag = false;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	private AlertDialog loginAlertDialog 		= null;
	private View dialog_login 						= null;
	private EditText dialog_etUser 					= null;
	private EditText dialog_etPw 					= null;
	
//	public void createLoginDialog()
//	{
//		View loginView 				= getLayoutInflater().inflate(R.layout.activity_signin, null);
//		dialog_login					= loginView.findViewById(R.id.signin_btnSignIn);
//		dialog_etUser 					= (EditText)loginView.findViewById(R.id.signin_etUser);
//		dialog_etPw					= (EditText)loginView.findViewById(R.id.signin_etPw);
//		loginAlertDialog 			= new AlertDialog.Builder(this).setView(loginView).create();
//		dialog_login.setOnClickListener(onClickListener);
//	}
	Animation loginViewAnimation = null;
	boolean FLAG_loginViewAnimation = false;
	public void showLoginDialog()
	{
		loginView.setVisibility(View.VISIBLE);
		if (!FLAG_loginViewAnimation){
			FLAG_loginViewAnimation = true;
			if ( loginViewAnimation == null ) {
				loginViewAnimation = new AlphaAnimation(0.0f, 1.0f);
				loginViewAnimation.setDuration(2000);
			}
			loginView.startAnimation(loginViewAnimation);
		}
	}
	DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			
		}
	};
	String username;
	String password;
	public boolean isLegalInput()
	{
		username = dialog_etUser.getText().toString().trim();
		if ( username.length() == 0 ) {
			//Toast.makeText(this, getResources().getString(R.string.tips_login_nameinput), Toast.LENGTH_SHORT).show();
			toastTxt.setText(getResources().getString(R.string.tips_login_nameinput));
			toast.setView(toastView);
			toast.show();
			return true;
		}
		password = dialog_etPw.getText().toString().trim();
		if ( password.length() == 0 ) {
			//Toast.makeText(this, getResources().getString(R.string.tips_login_pwinput), Toast.LENGTH_SHORT).show();
			toastTxt.setText(getResources().getString(R.string.tips_login_pwinput));
			toast.setView(toastView);
			toast.show();
			return true;
		}
		//密码长度不能少于6
		/*if ( password.length() < 6 ) {
			Toast.makeText(this, getResources().getString(R.string.tips_login_pwinput2), Toast.LENGTH_SHORT).show();
			return true;
		}*/
		return false;
	}
	Thread loginTask = null;
	public void loginTask()
	{
		if( ! NetHelper.isNetAble(MainActivity.this))
		{
			//Toast.makeText(this, "网络不好，请检查！", Toast.LENGTH_LONG).show();
			toastTxt.setText("check network connection!");
			toast.setView(toastView);
			toast.show();
			return;
		}
		if (  !isLegalInput() ) {
			InputMethodManager immInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			immInputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), 0);
			//wifiProgressDialog.show();
			loginDialog.show();
			//tv_progress.setText(getResources().getString(R.string.dialog_msg_load));
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (isDestroy) {
						return;
					}
					if ( ! isLogin) {
						//wifiProgressDialog.dismiss();
						if (loginDialog != null && loginDialog.isShowing())
							loginDialog.dismiss();
						new AlertDialog.Builder(MainActivity.this).setMessage("Invalid Connection!")
						.setNegativeButton("other net", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								openWifiLogin();
							}
						})
						.setPositiveButton("try again", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								loginTask();
							}
						}).show().setCanceledOnTouchOutside(false);
//						loginTask.interrupt();
					}
				}
			}, PublicInfo.MAX_TIME_WAITLAOD);
			isLogin = false;
			loginTask = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					String responString = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_login), username, password);
					Message msg = handler.obtainMessage(1);
					msg.obj = responString;
					handler.sendMessage(msg);
				}
			});
			loginTask.start();
		}
	}
	private boolean isLogin = false;
	OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if( v == dialog_login )
			{
				//友盟自定义事件
				MobclickAgent.onEvent(mContext, "user_login");
//				loginAlertDialog.hide();
				loginTask();
				
			}else if( v == wifiView )
			{
				MobclickAgent.onEvent(mContext, "wifi_login");
				openWifiLogin();
				//loginDialog.show();
			}else if( v == mainLayout ){
				//Toast.makeText(MainActivity.this, "Test", Toast.LENGTH_SHORT).show();
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		        imm.hideSoftInputFromWindow(dialog_etPw.getWindowToken(),0);
		        if (loginView.getVisibility() == View.INVISIBLE && !wifiNoticeDialog.isShowing()){
		        	if (WIFI_STATE == 1) {
		        		showLoginDialog();
		        	} else {
		        		if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
							wifiNoticeDialog.show();
						}
		        	}
		        }
			}else if( v == btn_progress )
			{
				//wifiProgressDialog.dismiss();
				loginDialog.dismiss();
			} else if (v == settingBtn) {
				Intent intent= new Intent(android.provider.Settings.ACTION_SETTINGS);
				startActivity(intent);
			}else if (v == WND_settingBtn) {
				openWifiLogin();
				uselocal =false;
				wifiNoticeDialog.dismiss();
			}else if (v == WND_useNoWifiBtn) {
				wifiNoticeDialog.dismiss();
				Componet userComponet = UserInfoManager.getInstance(MainActivity.this).getItem("username");
				if (userComponet == null){
					//Toast.makeText(MainActivity.this, "还没首次登陆，无法离线使用！", Toast.LENGTH_SHORT).show();
					toastTxt.setText("offline unavailable");
					toast.setView(toastView);
					toast.show();
					new InitializationTask().execute("");
					return;
				}
				uselocal = true;
				Intent localIntent = new Intent(MainActivity.this, PhotoFrameActivity.class);
				localIntent.putExtra("uselocal", true);
				startActivity(localIntent);
				Log.v(TAG, "执行startActivity(localIntent)");
				MainActivity.this.finish();
			}else if (v == BD_btn) {
				batteryDialog.dismiss();
			}
		}
	};
	public boolean ishaveOpenWifi = false;
	public void openWifiLogin()
	{
		//unregisterReceiver(receiver);
		ishaveOpenWifi = true;
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, WifiLoginActivity.class);
		startActivity(intent);
	}
	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			try {
				switch (what) {
				case 1:
					// 登录
					//wifiProgressDialog.dismiss();
					loginDialog.dismiss();
					JSONObject object = new JSONObject((String)msg.obj);
					if ( 0 == object.optInt("error", -1)) {
						if ( 1 == object.getJSONObject("data").getInt("return") )
						{
							// save m_auth
							Componet m_authComponet = new Componet("m_auth");
							m_authComponet.setValue(object.getJSONObject("data").getString("m_auth"));
							// save name
							Componet nameComponet = new Componet("name");
							nameComponet.setValue(object.getJSONObject("data").getString("name"));
							// save avatar
							Componet avatarComponet = new Componet("avatar");
							avatarComponet.setValue(object.getJSONObject("data").getString("avatar"));
							// save username  手机号码
							Componet usernameComponet = new Componet("username");
							usernameComponet.setValue(object.getJSONObject("data").getString("username"));
							// save uid
							Componet uidComponet = new Componet("uid");
							uidComponet.setValue(object.getJSONObject("data").getString("uid"));
							// save vip
							Componet vipComponet = new Componet("vip");
							vipComponet.setValue(object.getJSONObject("data").getString("vipstatus"));
							
							Componet preLoginUsername = UserInfoManager.getInstance(MainActivity.this).getItem("username");
							if( preLoginUsername != null &&
									! usernameComponet.getValue() .
									equals( preLoginUsername.getValue()))
							{
								// 与上一次登录不同
								ModelDataMgr.getInstance().clear(0);
								ModelDataMgr.getInstance().clear(1);
								ModelDataMgr.getInstance().clear(2);
								ModelDataMgr.getInstance().clear(3);
								ModelDataMgr.getInstance().clear(4);
								
							}
							UserInfoManager.getInstance(MainActivity.this).add(m_authComponet);
							UserInfoManager.getInstance(MainActivity.this).add(nameComponet);
							UserInfoManager.getInstance(MainActivity.this).add(avatarComponet);
							UserInfoManager.getInstance(MainActivity.this).add(usernameComponet);
							UserInfoManager.getInstance(MainActivity.this).add(uidComponet);
							UserInfoManager.getInstance(MainActivity.this).add(vipComponet);
//							Componet tempComponet = UserInfoManager.getInstance(SignInActivitiy.this).getItem("m_auth");
//							if ( tempComponet  != null ) {
////								UserInfoManager.getInstance(SignInActivitiy.this).delete(tempComponet);
//								tempComponet.setValue(m_authComponet.getValue());
//								Log.v("test", "xiugai:"+m_authComponet.getValue());
//							}else
//							{
//								UserInfoManager.getInstance(SignInActivitiy.this).add(m_authComponet);
//								Log.v("test", "new mauth:"+m_authComponet.getValue());
//							}
							UserInfoManager.getInstance(MainActivity.this).saveAll();
							FamilyDayVerPMApplication.bindJpush(MainActivity.this, uidComponet.getValue());
							downloadPicTask();
						}else
						{
							BD_notice.setText("Invalid Account Or Password!");
							batteryDialog.show();
							//new AlertDialog.Builder(MainActivity.this).setMessage(object.getString("msg")).setNeutralButton("确定", null).create().show();
						}
					}else {
						BD_notice.setText("Invalid Account Or Password!");
						batteryDialog.show();
						//new AlertDialog.Builder(MainActivity.this).setMessage(object.getString("msg")).setNeutralButton("确定", null).create().show();
					}
					isLogin = true;
					break;

				default:
					break;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		
		};
	};
	
	public  void notifyWifiChange()
	{
		if( uselocal )
		{
			return;
		}
		NetworkInfo.DetailedState state = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getDetailedState();
		String str_state = "";
		Log.v("wifi", "state:" + state.toString());
		if( state == NetworkInfo.DetailedState.CONNECTED )
		{
			str_state = "已连接";
			if (wifiProgressDialog.isShowing()) {
				wifiProgressDialog.dismiss();;
			}
			/*if( netErrorDialog.isShowing() )
			{
				netErrorDialog.hide();
			}*/
			if (wifiNoticeDialog != null && wifiNoticeDialog.isShowing()) {
				wifiNoticeDialog.dismiss();
			}
			if( loginView.getVisibility() == View.INVISIBLE )
			{
				onEnterFrame();
			}
			return;
		}else if(  state == NetworkInfo.DetailedState.CONNECTING )
		{
			str_state = "正在连接...";
		}else if(  state == NetworkInfo.DetailedState.BLOCKED )
		{
			str_state = "网络堵塞!";
		}else if(  state == NetworkInfo.DetailedState.AUTHENTICATING )
		{
			str_state = "正在认证...";
		}else if(  state == NetworkInfo.DetailedState.FAILED )
		{
			str_state = "连接失败！";
		}else if(  state == NetworkInfo.DetailedState.IDLE )
		{
			str_state = "正在准备数据连接配置...";
		}else if(  state == NetworkInfo.DetailedState.OBTAINING_IPADDR )
		{
			str_state = "正在获取IP地址...";
		}else if(  state == NetworkInfo.DetailedState.SUSPENDED )
		{
			str_state = "IP业务暂停！";
		}else if(  state == NetworkInfo.DetailedState.SCANNING )
		{
			str_state = "正在扫描...";
		}else if(  state == NetworkInfo.DetailedState.DISCONNECTING )
		{
			str_state = "正在断开当前连接...";
		}else if(  state == NetworkInfo.DetailedState.DISCONNECTED )
		{
//			str_state = "已关闭！";
			wifiProgressDialog.dismiss();
			/*if (!netErrorDialog.isShowing())
				netErrorDialog.show();*/
			if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
				wifiNoticeDialog.show();
			}
			return;
		}
		if( ! wifiProgressDialog.isShowing())
		{
			wifiProgressDialog.show();
		}
//		wifiProgressDialog.setMessage(str_state);
		tv_progress.setText(str_state);
	}
	public void downloadPicTask()
	{
		Intent intent = new Intent();
		intent.setClass(this, PhotoFrameActivity.class);
		intent.putExtra("uselocal", uselocal);
		intent.putExtra("isSaveMauth", isSaveMauth);
		startActivity(intent);
		Log.v(TAG, "执行startActivity(intent)");
		MainActivity.this.finish();
		//unregisterReceiver(receiver);
	}
	public void notifyWifiOpenChange() {
		// TODO Auto-generated method stub
		int state = wifiManager.getWifiState();
		String str_state = "";
    	switch (state) {
		case WifiManager.WIFI_STATE_ENABLING:
			str_state  = "正在打开wifi，请稍候...";
			break;
		case WifiManager.WIFI_STATE_ENABLED:
			str_state = "wifi初始化完毕，开始扫描...";
//			refreshWifiList();
			if (wifiProgressDialog.isShowing()) {
				wifiProgressDialog.dismiss();
				return;
			}
			break;
		case WifiManager.WIFI_STATE_UNKNOWN:
			str_state = "wifi初始化失败，正在重新打开...";
			if ( ! wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(true);
			}
			break;
		default:
//			tv_wifistate.setText("");
			break;
		}
    	if ( ! wifiProgressDialog.isShowing()) {
			wifiProgressDialog.show();
		}
//    	wifiProgressDialog.setMessage(str_state);
    	tv_progress.setText(str_state);
	}
	public void notifyFinishScan() {
		// TODO Auto-generated method stub
//		List<ScanResult> scanArrayList = wifiManager.getScanResults();
//		List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
//		if ( wifiConfigurations != null && wifiConfigurations.size() != 0 && scanArrayList!= null && scanArrayList.size() != 0) {
//			for (int i = 0; i < wifiConfigurations.size(); i++) {
//				for (int j = 0; j < scanArrayList.size(); j++) {
//					Log.v("wifi", "**" + scanArrayList.get(j).SSID + "&&" + wifiConfigurations.get(i).SSID );
//					if ( scanArrayList.get(j).SSID == wifiConfigurations.get(i).SSID )
//					{
//						waitConnect();
//						return;
//					}
//				}
//			}
//		}else
//		{
//			wifiProgressDialog.dismiss();;
//			netErrorDialog.show();
//		}
		if( wifiManager.getConfiguredNetworks() == null || wifiManager.getConfiguredNetworks().size() == 0 )
		{
			waitConnect(1000);
		}else
		{
			waitConnect(15*1000);
		}
	}
	boolean isDestroy = false;
	public void waitConnect(int time)
	{
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if( isDestroy )
				{
					return;
				}
				if ( ! NetHelper.isNetAble(MainActivity.this) )
				{
					wifiProgressDialog.dismiss();
					/*if (!netErrorDialog.isShowing())
						netErrorDialog.show();*/
					if (wifiNoticeDialog != null && !wifiNoticeDialog.isShowing()) {
						wifiNoticeDialog.show();
					}
				}
			}
		}, time);
	}
	
	
	public void myDelay(int time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
     * @param root 最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    private void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }
}
